package com.ph.shopping.facade.order.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ph.shopping.common.core.base.BaseService;
import com.ph.shopping.common.core.customenum.ResultEnum;
import com.ph.shopping.common.core.customenum.TransCodeEnum;
import com.ph.shopping.common.core.other.smssend.SmsCodeService;
import com.ph.shopping.common.util.page.PageBean;
import com.ph.shopping.common.util.result.Result;
import com.ph.shopping.common.util.transform.MoneyTransUtil;
import com.ph.shopping.facade.mapper.IOrderUnlineMapper;
import com.ph.shopping.facade.member.entity.Member;
import com.ph.shopping.facade.merchant.entity.Merchant;
import com.ph.shopping.facade.merchant.entity.UserBalance;
import com.ph.shopping.facade.merchant.entity.UserBalanceRecord;
import com.ph.shopping.facade.merchant.service.IMerchantService;
import com.ph.shopping.facade.merchant.service.IUserBalance;
import com.ph.shopping.facade.merchant.vo.MerchantDetaileVo;
import com.ph.shopping.facade.score.entity.PhScoreTotalTrade;
import com.ph.shopping.facade.score.service.IScoreService;
import com.ph.shopping.facade.score.vo.MemberScoreVo2;

import cm.ph.shopping.facade.order.entity.PhOrderUnline;
import cm.ph.shopping.facade.order.service.IUnLineOrerService;
import cm.ph.shopping.facade.order.vo.PhOrderUnlineVo;
import cm.ph.shopping.facade.order.vo.QueryMerchantOrderTakeVo;
import cm.ph.shopping.facade.order.vo.QueryWebUnLineOrderVo;
@Component
@Service(version="1.0.0")
public class IUnLineOrerServiceImpl extends BaseService implements IUnLineOrerService{


	@Autowired
	IOrderUnlineMapper iOrderUnlineMapper;
	
	@Reference(version="1.0.0")
	IUserBalance iUserBalance; 
		
	@Reference(version="1.0.0")
	IMerchantService  iMerchantService;
	
	@Reference(version="1.0.0")
	IScoreService iScoreService;
	
	@Autowired
	SmsCodeService smsCodeService;
	
	@Autowired
    private DataSourceTransactionManager txManager;
	
	
	/**
	 *线下订单List
	 */
	@Override
	public Result getUnLineOrderVoList(PhOrderUnlineVo phOrderUnlineVo, PageBean pagebean) throws Exception {
		PageHelper.startPage(pagebean.getPageNum(), pagebean.getPageSize());
		List<PhOrderUnlineVo> unLineOrderVoList = iOrderUnlineMapper.getUnLineOrderVoList(phOrderUnlineVo);
		for(PhOrderUnlineVo m : unLineOrderVoList){
			m.setOrderMoney(MoneyTransUtil.transDivisDouble(m.getOrderMoney1() == null ? 0 : m.getOrderMoney1()));
			m.setServiceCost(MoneyTransUtil.transDivisDouble(m.getServiceCost1() == null ? 0 : m.getServiceCost1()));
		}
		PageInfo<PhOrderUnlineVo>pageInfo=new PageInfo<PhOrderUnlineVo>(unLineOrderVoList);
		return getResult(ResultEnum.SUCCESS,pageInfo.getList(),pageInfo.getTotal());
	}	
	/**
	 * 创建线下订单
	 * @param phOrderUnline
	 * @return
	 */
	@Override
	@Transactional(rollbackFor=Exception.class)
	public Result addUnLineOrder(PhOrderUnline phOrderUnline) throws Exception{
		Result result = getResult(ResultEnum.SUCCESS); 
		try{
			//获取商户分润比率
			Merchant merchant = new Merchant();
			merchant.setId(phOrderUnline.getMerchantId());
			Result merchantDetailForUpdate = iMerchantService.getMerchantDetailForUpdate(merchant);
			Double businessProfitRatio = ((MerchantDetaileVo)(merchantDetailForUpdate.getData())).getBusinessProfitRatio();//得到分润比率
			phOrderUnline.setServiceCost(MoneyTransUtil.transMultiDouble(phOrderUnline.getOrderMoney()*businessProfitRatio));//服务费 
			phOrderUnline.setOrderMoney(phOrderUnline.getOrderMoney()*10000);
			
			phOrderUnline.setStatus(1);//1 订单完成 2 退货
			int orderUnlineId = iOrderUnlineMapper.insertOrderUnline(phOrderUnline);//创建订单 
			if(orderUnlineId !=1){
				logger.info("创建商户线下订单失败");
				return getResult(ResultEnum.ADD_MERCHANTUNLINEORDER_EXCEPTION);
			}
			if(phOrderUnline.getPayTpe() == 1){
	//			现金支付 目前不能调用接口没解决分布式事物处理问题
//				int userBalanceTrade = iUserBalance.userBalanceTrade(phOrderUnline.getMerchantId(), TransCodeEnum.MERCHANT_UNLINE_ORDER, 3, phOrderUnline.getOrderMoney().longValue(),null,phOrderUnline.getOrderNo());
	//			if(userBalanceTrade != 1){
	//				logger.info("现金支付失败");
	//				return getResult(ResultEnum.MERCHANT_MONEYPAY_FALIL_EXCEPTION);
	//			}
				
				//现金支付
				UserBalance userBalance = new UserBalance();
				userBalance.setManageId(phOrderUnline.getMerchantId());
				userBalance.setBalance(phOrderUnline.getOrderMoney().longValue());
				int updateUserBalance = iOrderUnlineMapper.updateUserBalance(userBalance);//修改余额
				if(updateUserBalance !=1){
					logger.info("修改商户余额失败");
					throw new Exception("修改商户余额失败");
				}
				UserBalanceRecord userBalanceRecord = new UserBalanceRecord();
				userBalanceRecord.setMoney((-phOrderUnline.getOrderMoney().longValue()));
				userBalanceRecord.setUserId(phOrderUnline.getMerchantId());
				userBalanceRecord.setType(6);
				userBalanceRecord.setTransCode(1008);
				userBalanceRecord.setOrderNo(phOrderUnline.getOrderNo());
				int insertUserBalanceRecord = iOrderUnlineMapper.insertUserBalanceRecord(userBalanceRecord);//记录流水
				if(insertUserBalanceRecord !=1){
					logger.info("修改商户余额记录流水失败");
					throw new Exception("修改商户余额记录流水失败");
				}
				
				
				//接下来执行赠送积分返回到待用积分(更新待用积分) 更新ph_member_score
//				iOrderUnlineMapper.updateMemberStandbyScore(phOrderUnline.getMemberId(), phOrderUnline.getOrderMoney().longValue());
//				//记入 总流水
//				PhScoreTotalTrade  totalTrade = new PhScoreTotalTrade(); 
//				totalTrade.setMemberId(phOrderUnline.getMemberId());
//				totalTrade.setOrderNo(phOrderUnline.getOrderNo());
//				totalTrade.setScore((phOrderUnline.getOrderMoney().longValue()));
//				totalTrade.setTransCode(1001);
//				int setId = iOrderUnlineMapper.insertMemberTrade(totalTrade);//记入总流水
//				if(setId  < 0){
//					logger.info("会员积分记入总流水失败");
//					throw new Exception("会员积分记入总流水失败");
//				}
//				//记入流水 入账流水 
//				int insertCostTrade = iOrderUnlineMapper.insertIncomeTrade(phOrderUnline.getMemberId(), 1001, (phOrderUnline.getOrderMoney().longValue()), totalTrade.getId(), phOrderUnline.getOrderNo());//记入支出流水
//				if(insertCostTrade  != 1){
//					logger.info("会员积分记入收入流水失败");
//					throw new Exception("会员积分记入收入流水失败");
//				}
				
				
				
			}else{
				//积分支付
//				long memberScoreTrade = iScoreService.memberScoreTrade(phOrderUnline.getMemberId(), TransCodeEnum.MEMBER_UNLINE_ORDER, phOrderUnline.getOrderMoney().longValue(), phOrderUnline.getOrderNo());
//				System.out.println("");
//				if(memberScoreTrade <= 0){
//					logger.info("积分支付失败");
//					return getResult(ResultEnum.SCORE_MERCHANTPAY_EXCEPTION);
//				}
				
				//这里跟新用户的可用积分减少  待会积分增加(改为待用积分不增加了 积分模块统一处理反积分)
				int updateMemberScore = iOrderUnlineMapper.updateMemberScore(phOrderUnline.getMemberId(), phOrderUnline.getOrderMoney().longValue(), (-phOrderUnline.getOrderMoney().longValue()), 0);//更新积分
				if(updateMemberScore !=1){
					logger.info("更新会员积分失败");
					throw new Exception("更新会员积分失败");
				}
				PhScoreTotalTrade  totalTrade = new PhScoreTotalTrade(); 
				totalTrade.setMemberId(phOrderUnline.getMemberId());
				totalTrade.setOrderNo(phOrderUnline.getOrderNo());
				totalTrade.setScore((-phOrderUnline.getOrderMoney().longValue()));
				totalTrade.setTransCode(1009);
				int setId = iOrderUnlineMapper.insertMemberTrade(totalTrade);//记入总流水
				if(setId  < 0){
					logger.info("会员积分记入总流水失败");
					throw new Exception("会员积分记入总流水失败");
				}
				int insertCostTrade = iOrderUnlineMapper.insertCostTrade(phOrderUnline.getMemberId(), 1009, (-phOrderUnline.getOrderMoney().longValue()), totalTrade.getId(), phOrderUnline.getOrderNo());//记入支出流水
				if(insertCostTrade  != 1){
					logger.info("会员积分记入支出流水失败");
					throw new Exception("会员积分记入支出流水失败");
				}
				
				
				//赠送积分的流水也要入库
//				totalTrade = new PhScoreTotalTrade(); 
//				totalTrade.setMemberId(phOrderUnline.getMemberId());
//				totalTrade.setOrderNo(phOrderUnline.getOrderNo());
//				totalTrade.setScore((phOrderUnline.getOrderMoney().longValue()));
//				totalTrade.setTransCode(1001);
//				setId = iOrderUnlineMapper.insertMemberTrade(totalTrade);//记入总流水
//				if(setId  < 0){
//					logger.info("会员积分消费赠送积分记入总流水失败");
//					throw new Exception("会员积分消费赠送积分记入总流水失败");
//				}
//				insertCostTrade = iOrderUnlineMapper.insertIncomeTrade(phOrderUnline.getMemberId(), 1001, (phOrderUnline.getOrderMoney().longValue()), totalTrade.getId(), phOrderUnline.getOrderNo());//记入支出流水
//				if(insertCostTrade  != 1){
//					logger.info("会员积分消费赠送积分记入收入流水失败");
//					throw new Exception("会员积分消费赠送积分记入收入流水失败");
//				}
				
				
			
			}			
			//接下执行此订单的积分赠送 现金支付才返积分  积分支付不返积分(有问题 剩余代用积分没加 强哥走起)
//			long memberScoreTrade2 = iScoreService.memberScoreTrade(phOrderUnline.getMemberId(),TransCodeEnum.MEMBER_BACK_SCORE,phOrderUnline.getOrderMoney().longValue(), phOrderUnline.getOrderNo());
//			if(memberScoreTrade2 <= 0){
//				logger.info("线下订单积分赠送失败");
//				throw new Exception("线下订单积分赠送失败");
//			}	
			//所有的执行都搞定 给用户来个短信吧
			try{
				sendMessageToMember(phOrderUnline.getOrderMoney().longValue(),phOrderUnline.getOrderNo(),phOrderUnline.getMemberId());
			}catch (Exception e){
				e.printStackTrace();
				logger.error("创建订单成功了给用户发短信有问题，短信接口有问题");
			}
		}catch (Exception e){
			e.printStackTrace();
			throw new Exception("创建订单失败");
		}
		
		return result ;
	}
	/**
	 *通过订单id获取订单
	 * @return
	 */
	@Override
	public PhOrderUnline getPhOrderUnlineById(PhOrderUnline phOrderUnline){
		return iOrderUnlineMapper.getPhOrderUnlineById(phOrderUnline);
	};
	
	/**
	 * 更新订单状态
	 */
	@Override
	public int updateUnlineOrderStatus(PhOrderUnline phOrderUnline){
		return iOrderUnlineMapper.updateUnlineOrderStatus(phOrderUnline);
	};
	/**
	 * 商户提货单
	 * @param queryMerchantOrderTakeVo
	 * @return
	 */
	@Override
	public Result getMerchantTakeOrderVoList(QueryMerchantOrderTakeVo queryMerchantOrderTakeVo, PageBean pagebean){
		PageHelper.startPage(pagebean.getPageNum(), pagebean.getPageSize());
		List<QueryMerchantOrderTakeVo> merchantTakeOrderVoList = iOrderUnlineMapper.getMerchantTakeOrderVoList(queryMerchantOrderTakeVo);
		for(QueryMerchantOrderTakeVo m : merchantTakeOrderVoList){
			m.setCommodityAmount(MoneyTransUtil.transDivisDouble(m.getCommodityAmount1() == null ? 0 :m.getCommodityAmount1()));
			m.setPostage(MoneyTransUtil.transDivisDouble(m.getPostage1() == null ? 0 :m.getPostage1() ));
			m.setPayMoney(MoneyTransUtil.transDivisDouble(m.getPayMoney1() == null ? 0 :m.getPayMoney1()));
		}
		
		PageInfo<QueryMerchantOrderTakeVo>pageInfo=new PageInfo<QueryMerchantOrderTakeVo>(merchantTakeOrderVoList);
		return getResult(ResultEnum.SUCCESS,pageInfo.getList(),pageInfo.getTotal());
	};
	
	/**
	 * 通过会员id 查询到此会员的线下订单供商城用
	 */
	@Override
	public  Result  queryWebUnLineOrders(Long memberId,Integer status ,Integer pageNum ,Integer pageSize ){
		PageHelper.startPage(pageNum, pageSize);
		List<QueryWebUnLineOrderVo> list = iOrderUnlineMapper.listWebUnLineOrders(memberId, status);
		if(list.size() < 0){
			logger.debug("未查询到会员的线下订单数据");
			return getResult(ResultEnum.NO_MEMBER_UNLINEORDER_EXCEPTION);
		}
		for (QueryWebUnLineOrderVo orderVo : list) {
			orderVo.setPayMoney(MoneyTransUtil.transDivisDouble(orderVo.getPayMoney1()));
		}
		PageInfo<QueryWebUnLineOrderVo> page = new PageInfo<QueryWebUnLineOrderVo>(list);
		return getResult(ResultEnum.SUCCESS, page.getList(), page.getTotal());
	};
	
	/**
	 * 创建线下订单成功了给用户发个短信吧
	 */
	public void sendMessageToMember(Long orderMoney,String orderNo,Long memberId){
		MemberScoreVo2 score = iOrderUnlineMapper.getScore(memberId);//获取用户积分
		Member memberInfo = iOrderUnlineMapper.getMemberInfo(memberId);//通过会员id获取会员信息
		String [] str = new String[5];
		str[0] = String.valueOf(MoneyTransUtil.transDivisDouble(orderMoney));
		str[1] = orderNo;
		str[2] = String.valueOf(MoneyTransUtil.transDivisDouble(orderMoney));
		str[3] = String.valueOf(MoneyTransUtil.transDivisDouble(score.getStandbyscore()));
		str[4] = String.valueOf(MoneyTransUtil.transDivisDouble(score.getEnablescore()));
		smsCodeService.sendSmsCodeByMsg(memberInfo.getMemberPhone(),str,14422);		
	}
}
